import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, logout, getUserInfo, register, updateUserProfile, updatePassword } from '@/api/user'
import { ActionContext } from 'vuex'
import router, { resetRouter } from '@/router'
import { RouteRecordRaw } from 'vue-router'
import request from '@/utils/request'

// 添加密码更新接口
interface PasswordUpdate {
  oldPassword: string
  newPassword: string
}

interface UserState {
  id: number | undefined
  counselorId: number | undefined
  studentId: number | undefined
  token: string | undefined
  name: string
  avatar: string
  role: string
}

// 定义 RootState 接口
interface RootState {
  user: UserState
  permission: {
    routes: RouteRecordRaw[]
  }
}

// 添加注册参数接口
interface RegisterInfo {
  username: string
  password: string
  realName: string
  phone: string
  email: string
}

interface LoginLogData {
  username: string
  ip: string
  userAgent: string
  status: number
  msg: string
}

const state: UserState = {
  id: undefined,
  counselorId: undefined,
  studentId: undefined,
  token: getToken(),
  name: '',
  avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
  role: '',
}

const mutations = {
  SET_TOKEN: (state: UserState, token: string) => {
    state.token = token
  },
  SET_ID: (state: UserState, id: number) => {
    state.id = id
  },
  SET_COUNSELOR_ID: (state: UserState, id: number) => {
    state.counselorId = id
  },
  SET_STUDENT_ID: (state: UserState, id: number) => {
    state.studentId = id
  },
  SET_NAME: (state: UserState, name: string) => {
    state.name = name
  },
  SET_AVATAR: (state: UserState, avatar: string) => {
    state.avatar = avatar
  },
  SET_ROLE: (state: UserState, role: string) => {
    state.role = role
  },
  SET_USER_INFO: (state: UserState, userInfo: Partial<UserState>) => {
    state.name = userInfo.name || ''
    state.avatar = userInfo.avatar || ''
    state.role = userInfo.role || ''
  }
}

interface LoginResponse {
  token: string
}

interface ApiError {
  message: string
  code: number
}


const actions = {
  // 登录
  login({ commit, dispatch }: any, userInfo: { username: string; password: string; remember: boolean }) {
    const { username, password, remember } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password, remember })
        .then(async response => {
          const { data } = response
          commit('SET_TOKEN', data.token)
          setToken(data.token, remember)
          resolve(data)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 获取用户信息
  async getInfo({ commit, state }: any) {
    try {
      // 从token中解析基本信息
      if (state.token && !state.id) {
        const token = state.token.replace('Bearer ', '')
        const payload = JSON.parse(atob(token.split('.')[1]))
        if (payload.userId) {
          commit('SET_ID', payload.userId)
        }
      }

      // 获取用户详细信息
      const response = await getUserInfo()
      const { data } = response

      if (!data) {
        throw new Error('获取用户信息失败，请重新登录')
      }

      const { id, name, avatar, role, counselorId, studentId } = data

      commit('SET_ID', id)
      commit('SET_NAME', name)
      commit('SET_AVATAR', avatar)
      commit('SET_ROLE', role)
      
      // 根据角色设置对应的ID
      if (role === 'counselor' && counselorId) {
        commit('SET_COUNSELOR_ID', counselorId)
      } else if (role === 'student' && studentId) {
        commit('SET_STUDENT_ID', studentId)
      }

      return data
    } catch (error) {
      console.error('获取用户信息失败:', error)
      throw error
    }
  },

  // 退出登录
  async logout({ commit, dispatch, state }: ActionContext<UserState, RootState>) {
    try {
      // 记录退出时间
      if (state.id) {
        await request({
          url: '/system/login/logout',
          method: 'post',
          data: {
            userId: state.id
          }
        })
      }
      
      await logout() // 调用退出登录 API
      
      // 清理用户状态
      removeToken()
      commit('SET_TOKEN', undefined)
      commit('SET_NAME', '')
      commit('SET_AVATAR', '')
      commit('SET_ROLE', '')
      
      // 重置路由
      resetRouter()
      
      // 重置权限路由
      commit('permission/SET_ROUTES', [], { root: true })
      
    } catch (error) {
      console.error('Logout failed:', error)
      throw error
    }
  },

  // 重置 Token
  resetToken({ commit }: ActionContext<UserState, any>) {
    removeToken()
    commit('SET_TOKEN', undefined)
    commit('SET_ROLE', '')
  },

  // 注册
  register({ }: ActionContext<UserState, any>, userInfo: RegisterInfo) {
    return new Promise((resolve, reject) => {
      register(userInfo).then(response => {
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  async updateProfile({ commit }: ActionContext<UserState, any>, userInfo: any) {
    try {
      await updateUserProfile(userInfo)
      // 更新成功后重新获取用户信息
      const { data } = await getUserInfo()
      commit('SET_USER_INFO', data)
      return Promise.resolve()
    } catch (error) {
      return Promise.reject(error)
    }
  },

  // 修改密码
  async updatePassword(
    { commit }: ActionContext<UserState, any>, 
    { oldPassword, newPassword }: PasswordUpdate
  ) {
    try {
      await updatePassword({ oldPassword, newPassword })
      return Promise.resolve()
    } catch (error) {
      return Promise.reject(error)
    }
  },

  // 记录登录日志
  recordLoginLog({ commit }: { commit: any }, logData: LoginLogData) {
    return request({
      url: '/system/login/log',
      method: 'post',
      data: logData
    })
  }
}

const getters = {
  userInfo: (state: UserState) => ({
    id: state.id,
    counselorId: state.counselorId,
    studentId: state.studentId,
    name: state.name,
    avatar: state.avatar,
    role: state.role
  })
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}